﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AliboboStockLib.date;
using AliboboStockLib.fetcher;
using AliboboStockLib.stockupdater.sbdetail;
using System.IO;



namespace AutoUpdateSB
{
    public partial class Form1 : Form
    {
        bool doAutoUpdate = true;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            processOTC();
        }
        protected void processStockDaily()
        {
            DateTime d = DateUtils.getValidTradeDate(DateTime.Now);
            DateTime realDate;
            List<List<String>> datas = TseDailyIndexFetcher.Fetch(d, out realDate, null);
            int c = TseDailyIndexUpdater.getCountOnDate(realDate);
            TseDailyIndexUpdater.updateStockDaily(realDate, datas, "tse", null);

        }
        protected int processSB()
        {
            int toProcessCount = 0;

            List<SBRecordState> SBTasks = null;
            DateTime d = TseDailyIndexUpdater.getMaxTradeDate();
            TseSBDetailUpdater updater = new TseSBDetailUpdater();
            SBTasks = updater.getCurrentSBStates(d);

            Tse_SB_Fetcher tseSBFetcher = new Tse_SB_Fetcher();
            DateTime vd = d.AddHours(16);
            TimeSpan ts = DateTime.Now.Subtract(vd);
            if (ts.TotalSeconds < 0)
            {
                MessageBox.Show("還沒到下午四點,無法處理");
                return 0;
            }


            if (SBTasks == null)
                return 0;


            String ds = DateUtils.getPlanString(d);
            String path = "d:\\SBdata\\" + ds + "\\";
            Directory.CreateDirectory(path);



            foreach (SBRecordState sbTask in SBTasks)
            {
                //把所有沒完成的都改成...代處理
                if (sbTask.處理進度.Equals(SBTaskState.完成)==false)
                {
                    //先回復
                    toProcessCount++;
                    sbTask.處理進度 = SBTaskState.待處理;
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                }
            }

            DateTime preD = DateTime.Now;
            foreach (SBRecordState sbTask in SBTasks)
            {
                if (sbTask.成交股數 == 0)
                    sbTask.處理進度 = SBTaskState.無資料;

                if (sbTask.處理進度.Equals(SBTaskState.待處理))
                {
                    sbTask.處理進度 = SBTaskState.抓取中;
                    try
                    {
                            SBRecords records = tseSBFetcher.CrawlingSB(sbTask.代號, d, sbTask.交易筆數);
                            if (records != null)
                            {
                                updater.updateSBDetails(records.SBEntries, sbTask.taskId, sbTask.代號, d);
                                sbTask.處理進度 = SBTaskState.完成;
                                updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                            }
                            else
                            {
                                sbTask.處理進度 = SBTaskState.錯誤;
                            }
                    }
                    catch (Exception e)
                    {
                        sbTask.處理進度 = SBTaskState.錯誤;
                        System.Diagnostics.Debug.WriteLine(e.Message);
                    }
                    sbTask.處理時間 = DateUtils.getYYYYMMDDHHSS(DateTime.Now);
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                }
                if (DateTime.Now.Subtract(preD).TotalSeconds > 1)
                {
                    Application.DoEvents();
                    preD = DateTime.Now;
                }
            }
            //處理紀錄 
            int total = SBTasks.Count;
            return toProcessCount;


        }
        protected void process()
        {
            DateTime d = DateTime.Now;
            if ((d.DayOfWeek.Equals(DayOfWeek.Saturday)) ||
                (d.DayOfWeek.Equals(DayOfWeek.Sunday)))
            {
                Application.Exit();
            }

            if (doAutoUpdate)
            {
                int processedTime = 0;
                try
                {
                    processStockDaily();

                    while (true)
                    {
                        processedTime++;
                        int c = processSB(); ;
                        if (c == 0)
                            break;
                        if (processedTime > 10)
                            break;
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                processOTC();

                Application.Exit();
            }

        }

        private static void processOTC(DateTime? dp=null)
        {
            
            int processedTime = 0;
            DateTime d2 = DateUtils.getValidTradeDate(DateTime.Now);
            OtcSBGetter otcSBGetter = new OtcSBGetter();

            if (null!=dp)
            {
                d2 = (DateTime)dp;
            }
            processedTime = 0;
            while (true)
            {
                otcSBGetter.process(d2);
                if (processedTime > 10)
                    break;
                processedTime++;
            }
        }

        
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            process();
        }
    }
}
